import axios from 'axios';
import { notification, message } from 'ant-design-vue';
import store from '../store';
let bulicurl = '/target';
const instance = axios.create({
	//创建axios实例，在这里可以设置请求的默认配置
	timeout: 10000 // 设置超时时间10s
});
// 文档中的统一设置post请求头。下面会说到post请求的几种'Content-Type'
instance.defaults.headers.post['Content-Type'] = 'application/json';
instance.defaults.headers.get['Content-Type'] = 'application/json';
let httpCode = {
	//这里我简单列出一些常见的http状态码信息，可以自己去调整配置
	400: '请求参数错误',
	401: '权限不足, 请重新登录',
	403: '服务器拒绝本次访问',
	404: '请求资源未找到',
	500: '内部服务器错误',
	501: '服务器不支持该请求中使用的方法',
	502: '网关错误',
	504: '网关超时'
};

/** 添加请求拦截器 **/
instance.interceptors.request.use(
	(config) => {
		message.loading('加载中...', 0);
		config.headers['Authorization'] = store.state.token;
		if (config.method == 'post') {
			config.params = {};
		}
		return config;
	},
	(error) => {
		// 对请求错误做些什么
		return Promise.reject(error);
	}
);

/** 添加响应拦截器  **/
instance.interceptors.response.use(
	(response) => {
        message.destroy();
		if (response.data.base.successCode == 0) {//成功
			return Promise.resolve(response.data);
		} else if (response.data.base.successCode == 1) {
            
			notification.error({
				message: '错误提示',
				description: response.data.base.successMsg,
				duration: 3
			});
			return Promise.reject(response.data.base.successMsg);
		} else if (response.data.base.successCode == 9) {
			notification.error({
				message: '错误提示',
				description: response.data.base.successMsg||'登陆过期请重新登录',
				duration: 3
            });
            store.commit("clearState")
			// setTimeout(function() {
			// 	window.location.href = '/login';
			// }, 1500);
			return Promise.reject(response.data.base.successMsg||'登陆过期请重新登录');
		}
	},
	(error) => {
		message.destroy();
		if (error.response) {
			// 根据请求失败的http状态码去给用户相应的提示
			let tips =
				error.response.status in httpCode ? httpCode[error.response.status] : error.response.data.message;
			notification.error({
				message: '消息提示',
				description: tips,
				duration: 3
			});

			return Promise.reject(error);
		} else {
			notification.error({
				message: '消息提示',
				description: '请求超时, 请刷新重试',
				duration: 3
			});
			return Promise.reject(new Error('请求超时, 请刷新重试'));
		}
	}
);
const ajax = (methodType, url, methodsParams, config) => {
	// 事件端口为11002  接口路径 /event/  ||  /electric/   //
	if (url.includes('/event/') || url.includes('/electric/')) {
		bulicurl = '/api';
	} else {
		bulicurl = '/target';
	}
	let base = store.state.userInfo || {};
	if (methodsParams && methodsParams.pageNum) {
		base.pageNum = methodsParams.pageNum;
		base.pageRows = methodsParams.pageRows;
	}
	let params = {
		// {"userRealName":"孙悟空","usertoken":"TOKEN:POLICE-0004:CJGLY-3:888888:8","userCode":"888888","userMobile":"13403404556"}
		base,
		buss: methodsParams || {}
	};
	return new Promise((resolve, reject) => {
		instance({
			method: methodType,
			url: `${bulicurl}${url}`,
			params: params,
			data: params,
			...config
		})
			.then((response) => {
				resolve(response);
			})
			.catch((error) => {
				reject(error);
			});
	});
};
const upFileFetch = ( url, methodsParams) => {
	// 事件端口为11002  接口路径 /event/  ||  /electric/   //
	if (url.includes('/event/') || url.includes('/electric/')) {
		bulicurl = '/api';
	} else {
		bulicurl = '/target';
	}
    let formData = new FormData();
    for(let attr in methodsParams){
        formData.append(attr,methodsParams[attr])
    }
    for (var [a, b] of formData.entries()) {
        console.log(a, b);
     } 
	return new Promise((resolve, reject) => {
		instance({
			method: "post",
			url: `${bulicurl}${url}`,
			data: formData,
			headers:{
                'Content-Type':'multipart/form-data',
                'Authorization':store.state.token
            }
		})
			.then((response) => {
				resolve(response);
			})
			.catch((error) => {
                console.log(`${bulicurl}${url}`,"接口有错误")
				reject(error);
			});
	});
};
export const get = (url, params, config = {}) => ajax('get', url, params, config);
export const post = (url, params, config = {}) => ajax('post', url, params, config);
export const upFile = (url,params)=> upFileFetch(url,params);
